/** 
 * 图片验证码组件
 */

import React, { useEffect, useRef } from 'react';
import { refreshCaptcha } from '../../services/utils';

export interface ICaptcha {
    refresh(): Promise<void> | void;
};

export type ImageCaptchaProps = {
    //props
    className?: string;
    onRefresh: () => Promise<string> | string;
    style?: React.CSSProperties;
    width?: number;
    height?: number;
}

export type ImageCaptchaState = {
    //states
    src: string | undefined;
}

class ImageCaptcha extends React.Component<ImageCaptchaProps> implements ICaptcha {

    state = {
        src: undefined,
    }

    constructor(props) {
        super(props);
    }

    refresh(): Promise<void> | void {

        const update = (img: string) => {
            if (this.state.src && this.state.src === img) {
                let url: string = img as string;
                if (url.indexOf('?') < 0) {
                    url += '?';
                } else {
                    url += '&';
                }
                url += '__csp=' + Date.now();
                img = url;
            }
            this.setState({
                src: img,
            });
        }

        const p = this.props.onRefresh();
        if (p instanceof Promise) {
            p.then(img => {
                update(img);
            });
        } else {
            update(p);
        }
    }

    render() {
        const { src } = this.state;
        const { className, style, width, height } = this.props;
        return <span className={`inline-block cursor-pointer ${className || ''}`} style={{ width: width || 132, height: height || 34, ...(style || {}) }} onClick={() => {
            this.refresh();
        }}>
            { src ? <img className="w-full h-full object-fill" src={src} /> : null }
        </span>;
    }
}

export type FormImageCaptchaProps = {
    value?: string;
    onChange?: (value: string) => void | Promise<void>;
    className?: string;
    style?: React.CSSProperties;
    width?: number;
    height?: number;
};

export const FormImageCaptcha: React.FC<FormImageCaptchaProps> = (props: FormImageCaptchaProps) => {
    const { onChange } = props;
    const ref = useRef<ImageCaptcha>(null);

    useEffect(() => {
        if (ref.current) {
            ref.current.refresh();
        }
    }, []);

    return <ImageCaptcha {...props} 
        ref={ref} 
        onRefresh={async () => {
            const { sessId, url } = await refreshCaptcha();
            onChange && onChange(sessId);
            return url;
        }} 
    />;
}

export default ImageCaptcha;
